<template>
    <!-- 筛选区 -->
   <div class="sub-filter">
     <div class="item" v-for="item in Category.saleProperties" :key="item.id">
       <div class="head">{{item.name}}</div>
       <div class="body">
         <a href="javascript:;" :class="{active:item.active===null}" @click="item.active=null,Filter({groupName:item.name,propertyName:null},id=null)">全部</a>
         <a href="javascript:;" :class="{active:value.active===value.id}" @click="value.active=value.id,Filter({groupName:item.name,propertyName:value.name},value.id)" v-for="value in item.properties" :key="value.id">{{value.name}}</a>
       </div>
     </div>
   </div>
</template>
<script>
import { useRoute } from 'vue-router'
import { useStore } from 'vuex'
import { watch, ref, reactive } from 'vue'
import { findSubCategoryFilter } from '@/api/category'

export default {
  name: 'SubFilter',
  setup (props, { emit }) {
    const router = useRoute()
    const store = useStore()
    const Category = ref([])
    const attrs = reactive({
      attrs: []
    })
    const Filter = (v, id) => {
      if (v.groupName === '品牌') {
        attrs.brandId = id
        return
      }
      const bol = attrs.attrs.find(res => res.groupName === v.groupName)
      if (bol) {
        if (bol.propertyName !== v.propertyName) {
          bol.propertyName = v.propertyName
        }
      } else {
        attrs.attrs.push(v)
      }
    }

    watch(attrs, () => {
      emit('attrs', { ...attrs })
    })

    watch([() => router.params.id, store.state.category], async () => {
      if (router.path === `/category/sub/${router.params.id}`) {
        const { result } = await findSubCategoryFilter(router.params.id)
        result.saleProperties.unshift({ id: null, name: '品牌', properties: [...result.brands] })
        result.saleProperties.forEach(item => {
          const active = ref(null)
          item.active = active
          item.properties.forEach(value => {
            value.active = active
          })
        })
        Category.value = result
      }
    }, {
      immediate: true
    })
    return { Category, Filter }
  }
}
</script>
<style scoped lang='less'>
  // 筛选区
  .sub-filter {
    background: #fff;
    padding: 25px;
    .item {
      display: flex;
      line-height: 40px;
      .head {
        width: 80px;
        color: #999;
      }
      .body {
        flex: 1;
        a {
          margin-right: 36px;
          transition: all .3s;
          display: inline-block;
          &.active,
          &:hover {
            color: @xtxColor;
          }
        }
      }
    }
  }
</style>
